<?php
header("content-type:text/html; charset=utf-8");
$app_config = require(dirname(__FILE__) . '/../config/boot.php');
require $app_config['QEEPHP_DIR'] . '/library/q.php';
require $app_config['APP_DIR'] . '/myapp.php';
$ret = MyApp::instance($app_config);
$userId = $_SESSION['attrID'];
$file_name = iconv("UTF-8","GB2312//IGNORE",$_REQUEST['fileName']);
$handle = fopen($file_name, "r");
$file_type = substr(strrchr($file_name, '.'), 1);
$number = str_replace('.txt', '', substr(strrchr($file_name, "\ "),1));
echo iconv("UTF-8","GB2312","进度:正在导入".$number."单号")."\r\n";
if ($file_type == 'xls')
{
	$data = Helper_BSS_XLS::xlsFileToArray($file_name, $handle);
}
else
{
	$buffer = array();
	if ($handle)
	{
		while ( ! feof($handle))
		{
			$buffer[] = fgets($handle, 4096);
		}
	}
	if ($buffer)
	{
		$data = array_chunk($buffer, 1);
	}
	else
	{
		$data = array();
	}
}
$sum = count($data)-1;//获取文件信息
//            echo $sum;
//            exit;
$qty = 0;
$pcs = 0;
$total_price = 0;
$stype = '';
$t = 0;
$cust_no = '';
foreach ($data as $key => $d)
{
	$d = array_values($d);
	$a = explode(',',$d[0]);
	$quantity = count($a);//echo $quantity;
	if ($quantity < 3)
	{
		echo   iconv("UTF-8","GB2312","第" . ($key+1) . "行未导入成功！:格式不正确。")."\r\n";
	}
	else
	{
		$k = explode(',', Helper_BSS_API::getk(trim($a[0])));
		if ($k[0] < 1)
		{
			echo  iconv("UTF-8","GB2312",'条码：'.$a[0].'无效')."\r\n";
		}
		else
		{
			$stype = $a[2];
			if ($k[1]>1)
			{
				$intquantity = $k[1];
			}
			else
			{
				$intquantity = 1;
			}
			switch (trim($a[2]))
			{
				case "#1":	//入库
					$inship = Inship::find('i_no=?',$number)->asArray()->getOne();
					if ($inship)
					{
						echo  iconv("UTF-8","GB2312","单号:" . $number . "已经存在")."\r\n";exit;
						QDB::getConn()->execute("delete from inship where i_no='". $number . "'");
					}
					QDB::getConn()->execute("insert into inshipdetail(i_no,barcode,k,qty,p_no) values('".$number."','".$a[0]."',".$k[0].",".$k[1].",'".$a[1]."')");
					$qty += $intquantity; //计算整张单的数量
					$pcs += 1; //计算件数
					//continue;//
					break;//这里使用continue
				case "#2":	//出库
					$outship = Ship::find('s_no=?',$number)->asArray()->getOne();
					if ($outship)
					{
						echo  iconv("UTF-8","GB2312",'单号：'.$number.'已存在1212121')."\r\n";exit;
					}
					$customer = Customer::find('c_no=?',$a[1])->asArray()->getOne();
					if (!$customer)
					{
						echo  iconv("UTF-8","GB2312",'单号'.$number.'客户：'.$a[1].'不存在')."\r\n";exit;
					}
					QDB::getConn()->execute('delete from ship where s_no=\''.$number.'\'');
					$inship = Inshipdetail::find($k[2])->asArray()->getOne();
					if (!$inship)
					{
						echo  iconv("UTF-8","GB2312",'单号：'.$number.'条码'.$a[0].'入库不存在')."\r\n";
					}
					else
					{
						QDB::getConn()->execute("insert into shipdetail(s_no,barcode,k,qty,qty_over,p_no) values('".$number."','".$a[0]."',".$k[0].",".$k[1].",".$k[1].",'".$inship['p_no']."')");
						$qty += $intquantity; //计算整张单的数量
						$pcs += 1; //计算件数
					}
					//continue;//
					break;
				case "#3":	//退货
					$outship = Reship::find('r_no=?',$number)->asArray()->getOne();
					if ($outship)
					{
						echo  iconv("UTF-8","GB2312",'单号：'.$number.'已存在')."\r\n";exit;
					}
					$customer = Customer::find('c_no=?',$a[1])->asArray()->getOne();
					if (!$customer)
					{
						echo  iconv("UTF-8","GB2312",'单号'.$number.'客户：'.$a[1].'不存在')."\r\n";exit;
					}
					$cust_no = $a[1];
					QDB::getConn()->execute('delete from reship where r_no=\''.$number.'\'');
					$reship = Shipdetail::find($k[2])->asArray()->getOne();
					if (!$reship)
					{
						echo  iconv("UTF-8","GB2312",'单号：'.$number.'条码'.$a[0].'入库不存在')."\r\n";
					}
					else
					{
						QDB::getConn()->execute("insert into reshipdetail(r_no,s_no,barcode,k,qty,p_no) values('".$number."','".$reship['s_no']."','".$a[0]."',".$k[0].",".$k[1].",'".$reship['p_no']."')");
						$qty += $intquantity; //计算整张单的数量
						$pcs += 1; //计算件数
					}
					//continue;//
					break;
				default://以前的l代表件数
					if ($t == 0)
					{
						$ship = Ship::find('s_no=?',$number)->setColumns('ship.s_no')->asArray()->getOne();
					}
					else
					{
						$ship = Ship1::find('s_no=?',$number)->setColumns('ship1.s_no')->asArray()->getOne();
					}
					if ($ship)
					{
						echo  iconv("UTF-8","GB2312",'单号'.$number.'已存在')."\r\n";exit;
					}
					$customer = Customer::find('c_no=?',$a[1])->asArray()->getOne();
					if (!$customer)
					{
						echo  iconv("UTF-8","GB2312",'单号'.$number.'客户：'.$a[1].'不存在')."\r\n";exit;
					}
					$product = Product::find('p_no=?',$a[2])->asArray()->getOne();
					if (!$product)
					{
						echo  iconv("UTF-8","GB2312",'单号'.$number.'产品'.$a[2].'不存在')."\r\n";
					}
					$p_price = $product['p_price']*$intquantity;
					$total_price += $p_price;
					$qty += $intquantity; //计算整张单的数量
					if ($t == 0)
					{
						$success = QDB::getConn()->execute('insert into shipdetail(s_no,barcode,k,qty,qty_over,p_price,p_no) values(\''.$number.'\',\''.$a[0].'\','.$k[0].','.$intquantity.','.$intquantity.','.$p_price.',\''.$a[2].'\')');
					}
					else
					{
						$success = QDB::getConn()->execute('insert into shipdetail1(s_no,barcode,k,qty,qty_over,p_price,p_no) values(\''.$number.'\',\''.$a[0].'\','.$k[0].','.$intquantity.','.$intquantity.','.$p_price.',\''.$a[2].'\')');
					}
					if ($success)
					{
						$pcs += 1; //计算件数
					}
					//dump($success);
					//echo  iconv("UTF-8","GB2312",'进来了没插入')."\r\n";
					//continue;
					break;
			}
		}
	}
	//				QDB::getConn()->execute("insert into salesman(sm_no,sm_addr) values ('2121212','".$a['0']."')");
	//				$order = Sales_Order::find('number=?', trim($d[0]))->getOne();
	//				if ($order['id'])
	//				{
	//					$order->tracking_number = trim($d[1]);
	//					$order->save();
	//				}
}
if ($pcs == 0)//插入总表
{
	echo iconv("UTF-8","GB2312",'单号'.$number.'无有效数据导入')."\r\n";
}
else
{
	switch ($stype)
	{
		case "#1":	//入库
			QDB::getConn()->execute('insert into inship(i_no,i_date,i_pcs,i_qty,i_entrydate,i_batchno,username) values(\''.$number.'\',\''.date('Y-m-d H:i:s', time()).'\','.$pcs.','.$qty.',\''.date('Y-m-d H:i:s', time()).'\',\''.$number.'\',\''.$userId.'\')');
			echo  iconv("UTF-8","GB2312",'单号：'.$number.'共['.$pcs.']条条码导入成功')."\r\n";
			break;
			//					case "#2":	//出库
			//						//QDB::getConn()->execute($sql);
			//
			//						break;
		case "#3":	//退货
			QDB::getConn()->execute('insert into reship(r_no,r_date,c_no,r_pcs,r_qty,username) values(\''.$number.'\',\'',date('Y-m-d H:i:s',time()).'\',\''.$cust_no.'\','.$pcs.','.$qty.',\''.$userId.'\')');
			echo  iconv("UTF-8","GB2312",'单号:'.$number.'共['.$pcs.']条条退货导入成功')."\r\n";
			break;
		default:
			if ($t == 0)
			{
				QDB::getConn()->execute('insert into ship(s_no,s_date,c_no,s_pcs,s_qty,s_qty_over,p_price,username) values(\''.$number.'\',\''.date('Y-m-d H:i:s',time()).'\',\''.$cust_no.'\','.$pcs.','.$qty.','.$qty.','.$total_price.',\''.$userId.'\')');
			}
			else
			{
				QDB::getConn()->execute('insert into ship1(s_no,s_date,c_no,s_pcs,s_qty,s_qty_over,p_price,c_no_p) values(\''.$number.'\',\''.date('Y-m-d H:i:s',time()).'\',\''.$cust_no.'\','.$pcs.','.$qty.','.$qty.','.$total_price.',\''.$userId.'\')');
			}
	}
	echo  iconv("UTF-8","GB2312",'单号：'.$number.'共['.$pcs.']条条码导入成功')."\r\n";
}
//		return $this->_redirectMessage('导入成功', '返回导入页面', url('Storage::Sales/ImportTrackingNumber'), $result['ack']);
echo iconv("UTF-8","GB2312",'单号：'.$number.'导入完成')."\r\n";;exit;